package com.study.web;

import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDate;

/**
 * 2022/5/8 20:25
 *
 * @author by yd
 */
@Api("转发和重定向测试")
@Slf4j
@Controller
@RequestMapping("forredir")
public class RedirectAndForController {

	@Autowired
	private HttpServletRequest request;
	@Autowired
	private HttpServletResponse response;

	@GetMapping("one")
	public void redirect(String name, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setAttribute("a", "a");
		Cookie cookie=new Cookie("one","one");
		response.addCookie(cookie);
		request.getRequestDispatcher("/forredir/two").forward(request, response);
	}

	@GetMapping("two")
	public void two(String name, HttpServletRequest request, HttpServletResponse response) throws IOException {
		log.info("two:[{}]", name);
		System.out.println(request.getAttribute("a"));
		System.out.println(request.getAttribute("b"));
		System.out.println(request.getContextPath());
		//重定向 需要 加上虚拟路径
		Cookie cookie=new Cookie("two","two");
		response.addCookie(cookie);
		response.sendRedirect(request.getContextPath() + "/forredir/three");
		// return "redirect:/forredir/three";
	}

	@ResponseBody
	@RequestMapping("three")
	public LocalDate three(String name) {
		log.info("three:[{}]", name);
		return LocalDate.now();
	}

}
